package com.bitcola.security.activity.controller;

import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.bitcola.security.activity.biz.BalanceChangeBiz;
import com.bitcola.security.activity.biz.RedPacketBiz;
import com.bitcola.entity.RedPacketHelp;
import com.bitcola.entity.RedPacketHelpLog;
import com.bitcola.security.activity.feign.IDataServiceFeign;
import com.bitcola.security.activity.mapper.ColaUserMapper;
import com.bitcola.security.activity.mapper.RedPacketHelpLogMapper;
import com.bitcola.security.activity.mapper.RedPacketHelpMapper;
import com.bitcola.security.auth.client.annotation.IgnoreUserToken;
import com.bitcola.security.common.context.BaseContextHandler;
import com.bitcola.security.common.msg.AppResponse;
import com.bitcola.security.common.util.IpUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("redPackHelp")
public class RedPackHelpController {
    @Autowired
    RedPacketHelpMapper redPacketHelpMapper;

    @Autowired
    RedPacketHelpLogMapper redPacketHelpLogMapper;

    @Resource
    IDataServiceFeign iDataServiceFeign;
    static Set<String>typeSet=new HashSet<>(5);

    static {

        typeSet.add("share");
        typeSet.add("kyc");
        typeSet.add("help");

    }



    @Autowired
    RedPacketBiz redPacketBiz;










    @RequestMapping(value = "help")
    public AppResponse help( HttpServletRequest request,String id){

        String ip= IpUtils.getIp(request);
        long now=System.currentTimeMillis();
        var userId=BaseContextHandler.getUserID();
        Example example=new Example(RedPacketHelpLog.class);
        example.createCriteria().andEqualTo("userId",userId);
        int count= redPacketHelpLogMapper.selectCountByExample(example);
        if(count>0)
            return AppResponse.ok().data( redPacketBiz.help(id,userId,"help",ip));
        else

            return AppResponse.ok().data( redPacketBiz.help(id,userId,"helpNew",ip));
    }


    @RequestMapping(value = "apply")
    public AppResponse apply() {

         var redPack= redPacketBiz.apply( BaseContextHandler.getUserID());
        return AppResponse.ok().data(redPack);


    }

    @RequestMapping(value = "withdraw")
    public AppResponse withdraw(String shareId) {
         var log= redPacketBiz.withdraw(shareId);
        return AppResponse.ok().data(log);
    }


        @RequestMapping(value = "share")
    public AppResponse share( HttpServletRequest request,String id) {
            String ip= IpUtils.getIp(request);

            var result= redPacketBiz.share(id, BaseContextHandler.getUserID(),ip);

        return AppResponse.ok().data(result);


    }


    @Autowired
    ColaUserMapper userMapper;

    @RequestMapping(value = "queryUserInfo",method = RequestMethod.POST)
    @Cached(expire = 10,cacheType = CacheType.LOCAL)
    public AppResponse queryUserInfo(@RequestBody Map<String,String> shareId) {

        String helpId=shareId.get("shareId");

        var  redPackpackage =redPacketHelpMapper.selectByPrimaryKey(helpId);
        if(redPackpackage!=null){
            var userId=redPackpackage.getUserId();
            return AppResponse.ok().data(userMapper.info(userId));


        }

        return AppResponse.ok().data(null);


    }









    @RequestMapping(value = "query")
    public AppResponse query(Boolean isPending)
    {

        Example example = new Example(RedPacketHelp.class);

        Example.Criteria criteria= example.createCriteria().andEqualTo("userId",BaseContextHandler.getUserID());

        if(isPending!=null&&isPending) {
          criteria.andLike("status","%SHARE%");

        }


        example.orderBy("createTime").desc();
       var list= redPacketBiz.selectByExample(example);
       list.stream().forEach(x->{
           if(x.getExpireTime().getTime()<System.currentTimeMillis()) x.setStatus("EXPIRE");
       });

        return AppResponse.ok().data(list);
    }


    @Autowired
    BalanceChangeBiz balanceChangeBiz;

    @RequestMapping(value = "queryLogs")
    public AppResponse queryLogs(int page,int size,String shareId)
    {
        RowBounds rowBounds=new RowBounds((page-1)*size,size);

        Example example = new Example(RedPacketHelpLog.class);

        example.createCriteria().andEqualTo("initiatorId",BaseContextHandler.getUserID()).andEqualTo("redPacketHelpId",shareId);
        example.orderBy("createTime").desc();
        var list= redPacketHelpLogMapper.selectByExampleAndRowBounds(example,rowBounds);
        var result= list.stream().map(x->{
            var map= BalanceChangeBiz.objectToMap(x);
            var user= userMapper.info(x.getUserId());
            map.put("icon",user.getAvatar());
            map.put("mobile",user.getTelPhone());
            map.put("email",user.getEmail());
            return map;



        }).collect(Collectors.toList());
        return AppResponse.ok().data(result);
    }


    @RequestMapping(value = "requestStage")
    @IgnoreUserToken
    public AppResponse requestStage(){

        Map<String,Object>result=new HashMap<>();
        result.put("logs",balanceChangeBiz.queryLast(30));
        result.put("sum",balanceChangeBiz.staticsRedPack());

        return AppResponse.ok().data(result);



    }
    @RequestMapping(value = "judgeRepeat",method = RequestMethod.POST)
    public AppResponse judgeRepeat(@RequestBody Map<String,String> share ){
        return AppResponse.ok().data(redPacketBiz.juedgeRepeat(BaseContextHandler.getUserID(),share.get("shareId")));


    }



}
